#-*-coding:utf-8-*-

import gevent
from gevent.queue import Queue, Empty

tasks = Queue(maxsize=3)

def worker(n):
    try:
        while True:
            task = tasks.get(timeout=1) # decrements queue size by 1
            print('Worker %s got task %s' % (n, task))
            gevent.sleep(0)
    except Empty:
        print('Quitting time!')

def boss():
    """
    Boss will wait to hand out work until a individual worker is
    free since the maxsize of the task queue is 3.
    """

    for i in xrange(1,10):
        tasks.put(i)
    print('Assigned all work in iteration 1')

    for i in xrange(10,20):
        tasks.put(i)
    print('Assigned all work in iteration 2')

if __name__ == "__main__":
	gevent.joinall([
		gevent.spawn(boss),
		gevent.spawn(worker, 'steve'),
		gevent.spawn(worker, 'john'),
		gevent.spawn(worker, 'bob'),
	])

"""
# 生产者消费者
1. gevent.spawn(funName,arg)
 funName 启动的函数名称
 arg 启动函数的参数,可以没有,或者多个

2. gevent.sleep(0)
 gevent睡眠,意味着停止当前这个协程,切换到写一个协程
 0秒之后,再次加入执行队列,轮到这个协程之后接着执行 sleep 后的代码

3. gevent.joinall() 和 gevent.join()
 join 和多线程中的 join 意思大致相同, 即主线程等待协程结束之后才可以结束
 joinall 参数是 list 可以是多个 gevent.spawn
 join 是一个 gevent.spawn
"""
